﻿using AutoMapper.Execution;
using Microsoft.EntityFrameworkCore;
using Quartz.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
using VOL.Entity.DomainModels.HealthEducation;
using VOL.SmartMecial.Dtos;
using VOL.SmartMecial.Infrastructure;
using VOL.SmartMecial.IServices.HealthEducation;
using Yitter.IdGenerator;

namespace VOL.SmartMecial.Services.HealthEducation
{
    /// <summary>
    /// 广播管理服务
    /// 提供广播模板、广播类型、广播管理等相关业务逻辑实现
    /// </summary>
    public class BroadManageService : IBroadManageService
    {
        private readonly IBaseRepository<BroadCastTemplate> _broadCastTemplateService;
        private readonly IBaseRepository<BroadType> _broadTypeService;
        private readonly IBaseRepository<BroadCastManage> _broadCastManageService;
        private readonly IBaseRepository<BroadCastModel> _broadCastRepository;
        private readonly IBaseRepository<BroadCasLog> _broadCasLogRepository;
        private readonly IBaseRepository<Sys_QuartzLog> _quartzLogRepository;


        /// <summary>
        /// 构造函数，通过依赖注入获取所需的仓储服务
        /// </summary>
        /// <param name="broadCastTemplateService">广播模板仓储服务</param>
        /// <param name="broadTypeService">广播类型仓储服务</param>
        /// <param name="broadCastManageService">广播管理仓储服务</param>
        /// <param name="broadCastRepository">广播模型仓储服务</param>
        /// <param name="bedRepository">床位仓储服务</param>
        public BroadManageService(IBaseRepository<BroadCastTemplate> broadCastTemplateService, IBaseRepository<BroadType> broadTypeService, IBaseRepository<BroadCastManage> broadCastManageService, IBaseRepository<BroadCastModel> broadCastRepository, IBaseRepository<BroadCasLog> broadCasLogRepository, IBaseRepository<Sys_QuartzLog> quartzLogRepository)
        {
            this._broadCastTemplateService = broadCastTemplateService;
            this._broadTypeService = broadTypeService;
            this._broadCastManageService = broadCastManageService;
            this._broadCastRepository = broadCastRepository;
            this._broadCasLogRepository = broadCasLogRepository;
            this._quartzLogRepository = quartzLogRepository;
        }

        /// <summary>
        /// 添加广播管理列表
        /// </summary>
        /// <param name="broadCastManageList">要添加的广播管理对象列表</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> AddBroadCastManageList(List<BroadCastManage> broadCastManageList)
        {
            try
            {
                var now = DateTime.Now;
                broadCastManageList.ForEach(o => o.CreateTime = now);
                int count = await _broadCastManageService.AddRange(broadCastManageList);
                return WebResponseContent.Instance.OK("添加成功", count);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"添加广播管理列表失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 添加广播管理列表
        /// </summary>
        /// <param name="broadCastManageList">要添加的广播管理对象列表</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> UpdBroadCastManageList(BroadCastManage broadCastManageList)
        {
            try
            {
 
                int count = await _broadCastManageService.UpdateAsync(broadCastManageList);
                return WebResponseContent.Instance.OK("修改成功", count);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"修改广播管理列表失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 获取广播列表
        /// </summary>
        /// <returns>广播列表数据及操作结果</returns>
        public async Task<WebResponseContent> GetBroadList()
        {
            try
            {
                var broadlist = _broadCastRepository.GetAll();
                return WebResponseContent.Instance.OK("查询成功", broadlist);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"获取广播列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取广播模板列表
        /// </summary>
        /// <returns>按层级结构组织的广播模板列表数据及操作结果</returns>
        public async Task<WebResponseContent> GetBroadCastTemplateList()
        {
            try
            {
                // 获取所有模板数据，只查询一次数据库
                var allTemplates = await _broadCastTemplateService.GetAll().ToListAsync();

                // 获取顶级模板(SortId=0)，并转换成DTO
                var rootTemplates = allTemplates
                    .Where(t => t.SortId == 0)
                    .Select(t => new BroadCastTemplateListDto
                    {
                        Value = t.Id,
                        Name = t.TemplateName,
                        Children = new List<BroadCastTemplateListDto>()
                    })
                    .ToList();

                // 获取子模板并添加到对应的父模板中
                var childTemplates = allTemplates.Where(t => t.SortId != 0);

                foreach (var child in childTemplates)
                {
                    var parent = rootTemplates.FirstOrDefault(r => r.Value == child.SortId);
                    if (parent != null)
                    {
                        parent.Children.Add(new BroadCastTemplateListDto
                        {
                            Value = child.Id,
                            Name = child.TemplateName,
                            Children = new List<BroadCastTemplateListDto>()
                        });
                    }
                }

                return WebResponseContent.Instance.OK("查询成功", rootTemplates);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"获取广播模板列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取广播类型列表
        /// </summary>
        /// <returns>广播类型列表数据及操作结果</returns>
        public async Task<WebResponseContent> GetBroadTypeList()
        {
            try
            {
                var broadTypeeList = _broadTypeService.GetAll();
                return WebResponseContent.Instance.OK("查询成功", broadTypeeList);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"获取广播类型列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 获取广播管理列表，包含关联信息
        /// </summary>
        /// <returns>广播管理列表数据及操作结果</returns>
        public async Task<WebResponseContent> GetBroadManageList()
        {
            try
            {
                var list = from b in _broadCastManageService.GetAll()
                           join t in _broadCastTemplateService.GetAll()
                           on b.BroadCastTypeId equals t.BroadCastTypeId
                           join p in _broadTypeService.GetAll()
                           on b.BroadCastTypeId equals p.Id
                           select new BroadManageListDto
                           {
                               Id = b.Id,
                               BordCastType = p.BroadTypeName,
                               Bed = b.BedId,
                               BroadCastContent = t.BroadCastContent,
                               TemplateName = t.TemplateName
                           };
                return WebResponseContent.Instance.OK("查询成功", list.Distinct());
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"获取广播管理列表失败: {ex.Message}");
            }
        }

        public Task<WebResponseContent> GetPatientsAndBed()
        {
            throw new NotImplementedException();
        }

        public async Task<WebResponseContent> AddBroadLog()
        {
            try
            {
                // 获取广播管理列表中的第一条记录
                var broadManage = await _broadCastManageService.GetAll().FirstOrDefaultAsync();
                if (broadManage == null)
                {
                    return WebResponseContent.Instance.Error("未找到可用的广播管理记录");
                }

                var broadLog = new BroadCasLog()
                {
                    BroadCastManageId = broadManage.Id,  // 使用查询到的ID而不是固定值
                    BoradCastTime = DateTime.Now,
                };
                var count = await _broadCasLogRepository.AddAsync(broadLog);
                return WebResponseContent.Instance.OK("添加成功", count);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"添加广播记录失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 展示广播模板列表树形下拉框
        /// </summary>
        /// <returns>按层级结构组织的广播模板列表数据及操作结果</returns>
        public async Task<WebResponseContent> ShowBroadCastTemplateList()
        {
            try
            {
                // 获取所有模板数据，只查询一次数据库
                var allTemplates = await _broadCastTemplateService.GetAll(x => x.IsUse == 1).ToListAsync();

                // 获取顶级模板(SortId=0)，并转换成DTO
                var rootTemplates = allTemplates
                    .Where(t => t.SortId == 0)
                    .Select(t => new BroadCastTemplateListDto
                    {
                        Value = t.Id,
                        Name = t.TemplateName,
                        Children = new List<BroadCastTemplateListDto>()
                    })
                    .ToList();

                // 获取子模板并添加到对应的父模板中
                var childTemplates = allTemplates.Where(t => t.SortId != 0 && t.IsUse == 1);

                foreach (var child in childTemplates)
                {
                    var parent = rootTemplates.FirstOrDefault(r => r.Value == child.SortId);
                    if (parent != null)
                    {
                        parent.Children.Add(new BroadCastTemplateListDto
                        {
                            Value = child.Id,
                            Name = child.TemplateName,
                            Url = child.FileUrl,
                            SortId = child.SortId,
                            BroadCastTypeId = child.BroadCastTypeId,
                            BroadCastContent = child.BroadCastContent,
                            IsUse = child.IsUse,
                            CreateTime = child.CreateTime,
                            Children = new List<BroadCastTemplateListDto>()
                        });
                    }
                }

                return WebResponseContent.Instance.OK("查询成功", rootTemplates);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error($"获取广播模板列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 添加宣教模板
        /// </summary>
        /// <param name="templateId">所属文件夹的ID</param>
        /// <returns>根据宣教模版父级文件夹的ID增加文件</returns>
        public async Task<WebResponseContent> CreateBroadCastTemplate(CreateBroadCastTemplateDTO createBroadCastTemplateDTO)
        {
            var ifBroadCastTemplate = _broadCastTemplateService.GetAll(m => m.FileUrl == createBroadCastTemplateDTO.FileUrl && m.SortId == createBroadCastTemplateDTO.SortId && m.IsUse == 1);
            if (ifBroadCastTemplate != null)
            {
                await _broadCastTemplateService.DelAll(m => m.FileUrl == createBroadCastTemplateDTO.FileUrl && m.SortId == createBroadCastTemplateDTO.SortId && m.IsUse == 1);
            }
            var FirstBroadCastTemplate = await _broadCastTemplateService.GetAll(m => m.Id == createBroadCastTemplateDTO.SortId).FirstOrDefaultAsync();
            var model = new BroadCastTemplate();
            model.TemplateName = createBroadCastTemplateDTO.TemplateName;
            model.BroadCastTypeId = FirstBroadCastTemplate.BroadCastTypeId;
            model.BroadCastContent = FirstBroadCastTemplate.BroadCastContent;
            model.FileUrl = createBroadCastTemplateDTO.FileUrl;
            model.SortId = FirstBroadCastTemplate.Id;
            model.IsUse = 1;
            model.CreateTime = DateTime.Now;
            var result = await _broadCastTemplateService.AddAsync(model);
            if (result > 0)
            {
                return WebResponseContent.Instance.OK("添加成功", result);

            }
            else
            {
                return WebResponseContent.Instance.Error("添加失败");
            }
        }

        /// <summary>
        /// 父级下拉框
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> GetBroadCastTemplateDad()
        {
            var result = await _broadCastTemplateService.GetAll(m => m.SortId == 0 && m.IsUse == 1).ToListAsync();
            return WebResponseContent.Instance.OK(null, result);

        }

        /// <summary>
        /// 修改宣教模板
        /// </summary>
        /// <param name="Id">需要修改的ID</param>
        /// <returns></returns>
        public async Task<WebResponseContent> UpdateBroadCastTemplate(BroadCastTemplate broadCastTemplate)
        {
            var GetbroadCastTemplate = await _broadCastTemplateService.FindAsync(broadCastTemplate.Id);
            GetbroadCastTemplate.CreateTime = DateTime.Now;
            var result = await _broadCastTemplateService.UpdateAsync(broadCastTemplate);
            return WebResponseContent.Instance.OK(null, result);

        }

        /// <summary>
        /// 逻辑删除宣教模板
        /// </summary>
        /// <param name="broadCastTemplateid"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> DeleteBroadCastTemplate(int broadCastTemplateid)
        {
            var getbroadCastTemplate = await _broadCastTemplateService.FindAsync(broadCastTemplateid);
            int getBroadCastTemplateNum = _broadCastTemplateService.GetAll(m => m.SortId == broadCastTemplateid).Count();
            if (getBroadCastTemplateNum > 0)
            {
                return WebResponseContent.Instance.Error("当前文件夹下已有文件，请先删除文件后再删除文件夹");
            }
            getbroadCastTemplate.IsUse = 0;
            var result = await _broadCastTemplateService.UpdateAsync(getbroadCastTemplate);
            return WebResponseContent.Instance.OK("删除成功", result);
        }
        public async Task<WebResponseContent> GetBroadLogList()
        {
            //var dtoList = from l in _broadCasLogRepository.GetAll()
            //              join m in _broadCastManageService.GetAll() on l.BroadCastManageId equals m.Id
            //              join t in _broadTypeService.GetAll() on m.BroadCastTypeId equals t.Id
            //              join tmp in _broadCastTemplateService.GetAll() on t.Id equals tmp.BroadCastTypeId
            //              select new BroadLogDto
            //              {
            //                  Id = l.Id,
            //                  BoradCastTime = l.BoradCastTime,
            //                  BroadTypeName = t.BroadTypeName,
            //                  BroadContent = tmp.BroadCastContent,
            //              };
            //dtoList = dtoList.WhereIF(dto.StartTime != null, o => o.BoradCastTime >= dto.StartTime);
            //dtoList = dtoList.WhereIF(dto.EndTime != null, o => o.BoradCastTime <= dto.StartTime);
            //dtoList = dtoList.WhereIF(!string.IsNullOrEmpty(dto.Content), o => o.BroadContent.Contains(dto.Content));
            var list = _quartzLogRepository.GetAll();
            var response = WebResponseContent.Instance.OK("查询成功", list);

            return response;

        }
        /// <summary>
        /// 删除广播管理
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> DelBroadManage(int id)
        {
            var broadManage = await _broadCastManageService.GetAll().FirstOrDefaultAsync(m => m.Id == id);
            await _broadCastManageService.Remove(broadManage);
            var response = WebResponseContent.Instance.OK("删除成功");
            return response;
        }

        public async Task<WebResponseContent> GetBroadManageModel(int id)
        {
            var broadManage = await _broadCastManageService.GetAll().FirstOrDefaultAsync(m => m.Id == id);
            var response = WebResponseContent.Instance.OK("查询成功", broadManage);
            return response;
        }
    }
}
